<template>
  <el-card class="box-card" shadow="always">
    <!--1.面包屑-->
    <!--首页/用户管理/用户列表-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--2.搜索框-->
    <el-row class="searchRow">
      <el-col>
        <el-input
          placeholder="请输入内容"
          clearable
          v-model="queryInfo.query"
          class="inputSearch">
          <el-button slot="append" icon="el-icon-search" @click="queryByUsername()"></el-button>
        </el-input>
        <el-button type="success" @click="addUserShow()">添加用户</el-button>
      </el-col>
    </el-row>
    <!--用户列表表格-->
    <el-table
      :data="userList"
      style="width: 100%">
      <el-table-column
        type="index"
        align="center"
        label="序号"
        width="60">
      </el-table-column>
      <el-table-column
        prop="username"
        align="center"
        label="姓名"
        width="80">
      </el-table-column>
      <el-table-column
        align="center"
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        align="center"
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="create_time"
        align="center"
        label="创建时间">
        <template slot-scope="scope">
          {{scope.row.create_time | fmtdate}}
        </template>
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="用户权限">
      </el-table-column>
      <el-table-column
        prop="mg_state"
        align="center"
        label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="changeUserStatus(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop=""
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="修改" :enterable="false" placement="top">
          <el-button type="primary" size="mini" icon="el-icon-edit" plain circle @click="modifyUserInfoShow(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" :enterable="false" placement="top">
          <el-button type="danger" size="mini" icon="el-icon-delete" plain circle @click="deleteUser(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="角色分配" :enterable="false" placement="top">
            <el-button type="info" size="mini" icon="el-icon-setting" plain @click="distributionPermissions(scope.row)" circle></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
     <div class="block">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
    <!--添加用户弹窗-->
    <el-dialog title="添加用户" :visible.sync="dialogAddUserFormVisible">
      <el-form :model="addUserRuleForm" :rules="rules" ref="addUserRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddUserFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </div>
    </el-dialog>
<!--    编辑用户弹窗-->
    <el-dialog
      title="修改用户信息"
      :visible.sync="modifyDialogVisible"
      width="50%"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addUserRuleForm"
        ref="addUserRuleForm"
        :rules="rules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="addUserRuleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyUserInfo">确 定</el-button>
      </span>
    </el-dialog>
<!--    用户角色分配-->
    <el-dialog
      title="分配角色"
      :visible.sync="distributionDialogVisible"
      width="50%"
    >
      <!-- 内容主体 -->
      <el-form
        :model="distributionForm"
        label-width="70px"
      >
        <el-form-item label="用户名">
          {{distributionForm.username}}
        </el-form-item>
        <el-form-item label="角色" prop="email">
          <el-select clearable v-model="distributionForm.rid" placeholder="请选择">
            <el-option
              v-for="item in distributionOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="distributionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="distributionUserInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
  export default {
    data () {
      return {
        queryInfo:{
          query: '',
          pagenum: 1,
          pagesize: 5,
        },
        userList: [],
        total:1,
        //添加用户弹窗
        dialogAddUserFormVisible:false,
        addUserRuleForm:{
          username:"",
          password:"",
          email:"",
          mobile:""
        },
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
        },
        //修改用户信息相关
        modifyDialogVisible:false,
        userId:'',
        //用户角色分配
        distributionDialogVisible:false,
        distributionForm:{
          id:'',
          username:'',
          rid:''
        },
        distributionOptions:[
          {
            value:'',
            label:'',
          }
        ]
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      async getUserList () {
        //需要授权的API 必须在请求头中使用 Authorization 字段 提供 token 令牌
        const AUTH_TOKEN = localStorage.getItem('token')
        this.$http.defaults.headers.common['Authorization'] = AUTH_TOKEN
        const res = await this.$http.get('users', {params:this.queryInfo})
        console.log(res)
        if (res.status===200){
          this.userList = res.data.data.users;
          this.total = res.data.data.total;
          this.$message.success(res.data.meta.msg)
        }else{
          this.$message.error(res.data.meta.msg)
        }
      },
      //分页
      //监听pagesize变化
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList();
      },
      //监听 页码值
      handleCurrentChange(newSize) {
        this.queryInfo.pagenum = newSize
        this.getUserList();
      },
      //搜索用户
      queryByUsername(){
        this.getUserList()
      },
      //添加用户方法
      addUserShow(){
        Object.assign(this.$data.addUserRuleForm,this.$options.data().addUserRuleForm)
        this.dialogAddUserFormVisible = true
      },
      async addUser(){
        const res = await this.$http.post('users',this.addUserRuleForm)
        console.log(res,'添加用户')
        if (res.status===200){
          this.$message.success(res.data.meta.msg)
          this.getUserList()
          this.dialogAddUserFormVisible = false
        }else {
          this.$message.error(res.data.meta.msg)
        }
        //清空表单数据
        Object.assign(this.$data.addUserRuleForm,this.$options.data().addUserRuleForm)
      },
      //删除用户
      deleteUser(row){
        const id = row.id
        this.$confirm('删除用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete('users/'+id).then(res=>{
            if (res.status !== 200) {return this.$message.error('删除用户失败！')}
            this.$message.success('删除用户成功！')
            //页面数据刷新
            this.getUserList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //修改用户信息 密码不允许在此处修改
      modifyUserInfoShow(row){
        this.modifyDialogVisible = true
        this.addUserRuleForm.username = row.username
        this.addUserRuleForm.email = row.email
        this.addUserRuleForm.mobile = row.mobile
        this.userId = row.id
      },
      modifyUserInfo(){
        this.$http.put('users/'+this.userId,this.addUserRuleForm).then(res=>{
          console.log(res,'打印修改用户信息')
          if (res.status===200){
            this.$message.success("修改成功")
            //数据刷新
            this.getUserList()
          }else{
            this.$message({
              message:'修改失败',
              type:'warning'
            })
          }
        })
        this.modifyDialogVisible = false
        //修改完成后清空表单数据
        Object.assign(this.$data.addUserRuleForm,this.$options.data().addUserRuleForm)
      },
      //修改用户状态
      changeUserStatus(row){
        this.$http.put(`users/${row.id}/state/${row.mg_state}`).then(res=>{
          console.log(res,'打野修改用户状态信息')
          if (res.status===200){
            this.$message.success('用户状态变更成功')
            this.getUserList()
          }else {
            this.$message.error('用户状态变更成功')
          }
        })
      },
      //用户角色分配
      distributionPermissions(row){
        this.distributionDialogVisible = true
        this.distributionForm.username = row.username
        this.distributionForm.id = row.id
        //获取角色列表
        this.$http.get('roles').then(res=>{
          console.log(res,'获取角色列表')
          this.distributionOptions = res.data.data
        })
        //获取当前用户角色`users/${row.id}`
        this.$http.get(`users/${row.id}`).then(res=>{
          console.log(res,'获取当前用户的角色')
          //res.data.data.rid
          this.distributionForm.rid = res.data.data.rid
        })
      },
      distributionUserInfo(){
        this.distributionDialogVisible = false
        this.$http.put(`users/${this.distributionForm.id}/role`,{
          rid:this.distributionForm.rid
        }).then(res=>{
          console.log(res,'用户角色分配提交')
          if(res.status===200){
            this.$message({
              message:res.data.meta.msg,
              type:'success'
            })
          }else {
            this.$message({
              message:'角色分配失败',
              type:'warning'
            })
          }
        })
        //数据刷新
        this.getUserList()
      }
    }
  }
</script>
<style>
  .box-card {
    height: 100%;
  }

  .inputSearch {
    width: 300px;
  }

  .searchRow {
    margin-top: 20px;
  }
</style>
